<template>
    <div class="plot-person">
        <el-row>
            <el-col :span="24">
                <!-- 筛选表单 -->
                <el-form ref="queryFormRef" :model="queryForm" inline size="mini">
                    <el-form-item label="人员名称">
                        <el-input v-model="queryForm.name" placeholder="人员名称" />
                    </el-form-item>
                    <el-form-item label="人员类型">
                        <el-select v-model="queryForm.roleId" placeholder="请选择">
                            <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName"
                                :value="item.roleId" />
                        </el-select>
                    </el-form-item>
                    <el-button type="primary" @click="handleQuery" size="small">查询</el-button>
                    <el-button plain @click="handleReset" size="small">重置</el-button>
                    <el-button type="primary" plain @click="handleAdd" size="small">添加</el-button>
                </el-form>

                <!-- 人员列表表格 -->
                <el-table :data="personList" border stripe style="width: 100%;" ref="table"
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="50" />
                    <el-table-column type="index" label="序号" width="50" align="center" />
                    <el-table-column prop="name" label="人员姓名" align="center" />
                    <el-table-column prop="phoneNumber" label="电话" align="center" />
                    <el-table-column prop="cardId" label="身份证" show-overflow-tooltip align="center" />
                    <el-table-column prop="roleName" label="人员类型" align="center" />
                    <el-table-column label="操作" width="200" align="center">
                        <template #default="{ row }">
                            <el-button type="primary" size="small" @click="handleEdit(row.personId)">编辑</el-button>
                            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页组件 -->
                <el-pagination @size-change="handleSizeChange" @current-change="handlePageChange"
                    :current-page.sync="paginate.pageNum" :page-sizes="[10, 20, 30]" :page-size.sync="paginate.pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="paginate.total" />

                <!-- 新增/编辑弹窗 -->
                <el-dialog :visible.sync="dialog.visible" width="50%">
                    <template #title>{{ dialog.isEdit ? "编辑人员" : "添加人员" }}</template>
                    <el-form :model="dialog.form" :rules="dialog.rules" ref="dialogForm">
                        <el-form-item label="人员姓名" prop="name">
                            <el-input v-model="dialog.form.name" />
                        </el-form-item>
                        <el-form-item label="电话" prop="phoneNumber">
                            <el-input v-model="dialog.form.phoneNumber" />
                        </el-form-item>
                        <el-form-item label="身份证" prop="cardId">
                            <el-input v-model="dialog.form.cardId" />
                        </el-form-item>
                        <el-form-item label="人员类型" prop="roleId">
                            <el-select v-model="dialog.form.roleId" placeholder="请选择">
                                <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName"
                                    :value="item.roleId" />
                            </el-select>
                        </el-form-item>
                    </el-form>
                    <span slot="footer">
                        <el-button @click="dialog.visible = false">取消</el-button>
                        <el-button type="primary" @click="handleSubmit">确定</el-button>
                    </span>
                </el-dialog>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import { getPersonList, getPersonType, getPersonDetail, addPersonInfo, updatePersonInfo, deletePersonInfo } from '@/api/person';
import { checkQueryInput, restForm } from '@/utils/tool'

export default {
    name: 'PlotPerson',
    data() {
        return {
            // 锁
            isLock: false,

            // 人员列表
            personList: [],

            // 人员类型下拉选项
            roleList: [],


            queryForm: {
                name: '',
                roleId: ''
            },

            // 分页数据
            paginate: {
                pageNum: 1,
                pageSize: 10,
                total: 0
            },

            // 弹窗
            dialog: {
                visible: false,
                isEdit: false,

                form: {
                    personId: '',
                    name: '',
                    phoneNumber: '',
                    cardId: '',
                    roleId: '',
                    plotId: ''
                },

                rules: {
                    name: [{ required: true, message: '请输入人员姓名', trigger: 'blur' }],
                    phoneNumber: [{ required: true, message: '请输入电话', trigger: 'blur' }],
                    cardId: [{ required: true, message: '请输入身份证', trigger: 'blur' }],
                    roleId: [{ required: true, message: '请选择人员类型', trigger: 'change' }]
                }
            },

            // 批量删除
            ids: [],//存储选中的所有小区ID
            single: true,//标记是否不是单选
            multiple: false//标记是否没有选中数据
        }
    },

    created() {
        // 初始化时获取当前小区 ID
        const plotId = this.$store.state.plot?.currentPlot?.plotId || undefined


        if (plotId) {
            this.dialog.form.plotId = plotId;
            this.updatePersonList(plotId);
            this.updateRoleList();
        }

        // 监听小区id变化
        this.$watch(
            function () {
                return this.$store.state.plot?.currentPlot?.plotId
            }.bind(this), //把this绑定到组件实例，不然function中的this会丢失

            function (newPlotId) {
                const plotId = newPlotId || undefined

                // 如果小区id有值，则加载人员列表和人员类型列表
                if (plotId) {
                    this.dialog.form.plotId = plotId
                    this.updatePersonList(plotId)
                    this.updateRoleList()
                }
            }.bind(this)
        )
    },

    computed: {
        currentPlotId() {
            return this.$store.state.plot?.currentPlot?.plotId || undefined
        }
    },

    methods: {
        // 加载人员列表
        updatePersonList(plotId) {
            const { total, ...rest } = this.paginate
            const params = {
                ...rest,
                plotId,
                // ...this.queryForm
            }
            return getPersonList(params).then(res => {
                this.personList = res.rows || [];
                this.paginate.total = res.total || 0
                // console.log("人员列表", res);
            })
        },

        // 加载人员类型下拉列表
        updateRoleList() {
            getPersonType().then(res => {
                this.roleList = res.data || [];
            })
        },

        // 分页切换
        handleSizeChange(size) {
            this.paginate.pageSize = size
            this.updatePersonList(this.currentPlotId)
        },
        handlePageChange(page) {
            this.paginate.pageNum = page
            this.updatePersonList(this.currentPlotId)
        },

        // 查询
        handleQuery() {
            const hasInput = checkQueryInput(this.queryForm)
            if (!hasInput) return this.$message.warning("当前没有输入值，请至少输入一项数据!!")
            this.paginate.pageNum = 1;
            this.updatePersonList(this.currentPlotId).then(() => {
                this.$message.success("查询成功")
            })
        },

        // 重置
        handleReset() {
            restForm(this.$refs.queryFormRef)
            this.queryForm = { name: '', roleId: '' }
            this.paginate.pageNum = 1
            this.updatePersonList(this.currentPlotId).then(() => {
                this.$message.success("操作成功")
            })
        },

        // 添加
        handleAdd() {
            this.dialog.visible = true;
            this.dialog.isEdit = false;
            this.dialog.form = {
                plotId: this.currentPlotId,
                name: '',
                phoneNumber: '',
                cardId: '',
                roleId: ''
            };
        },

        // 编辑
        handleEdit(personId) {
            getPersonDetail(personId).then(res => {
                this.dialog.visible = true;
                this.dialog.isEdit = true;
                this.dialog.form = { ...res.data, plotId: this.currentPlotId };
            })
        },

        // 提交
        handleSubmit() {
            if (this.isLock) return

            this.$refs.dialogForm.validate(valid => {
                if (!valid) return
                this.isLock=true
                const api = this.dialog.isEdit ? updatePersonInfo : addPersonInfo
                api(this.dialog.form).then(() => {
                    this.dialog.visible = false;
                    this.updatePersonList(this.currentPlotId);
                    this.$message.success('操作成功')
                    this.isLock=false
                })
            });
        },

        // 批量删除的选中事件
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.personId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },

        // 删除人员
        handleDelete(row) {
            // 拿到被选中的人员的id
            const personIds = this.ids.length > 0 ? this.ids : [row.personId]

            const personIdsStr = personIds.join(',')

            // 获取选中的数量
            const count = personIds.length

            this.$confirm(`确定删除选中的【${count}】名人员吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                return deletePersonInfo(personIdsStr).then(() => {
                    this.updatePersonList(this.currentPlotId);
                    this.$message.success('删除成功')
                    this.$refs.table.clearSelection()
                })
            }).catch((err) => {
                console.log(err);
            })
        }
    }
};
</script>

<style lang="scss" scoped>
.plot-person {
    padding: 20px;
}
</style>